﻿// -------------------------------------------------------------------------
//    @FileName         :    TestNFShmHashMultiMapWithList.h
//    @Author           :    Assistant
//    @Date             :    25-9-25
//    @Email            :    assistant@openai.com
//    @Module           :    TestNFShmHashMultiMapWithList
//
// -------------------------------------------------------------------------

#pragma once

#include <gtest/gtest.h>
#include "NFComm/NFShmStl/NFShmHashMultiMapWithList.h"
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <set>

/**
 * @file TestNFShmHashMultiMapWithList.h
 * @brief NFShmHashMultiMapWithList的单元测试，重点测试新增的value排序功能
 * 
 * 测试覆盖范围：
 * 1. sort_list() - 按值升序排序 (多重映射特性)
 * 2. sort_list() - 按值降序排序
 * 3. sort_list(comp) - 使用自定义比较器按值排序
 * 4. 多重映射中相同key不同value的排序行为
 * 5. 与原有sort_list()的兼容性测试
 * 6. 复杂场景下的排序稳定性
 */

// ==================== 测试用数据结构 ====================

/**
 * @brief 用于测试的成绩信息结构
 */
struct ScoreInfo
{
    std::string subject;
    int score;
    std::string semester;

    ScoreInfo() : score(0)
    {
    }

    ScoreInfo(const std::string& sub, int sc, const std::string& sem) : subject(sub), score(sc), semester(sem)
    {
    }

    bool operator==(const ScoreInfo& other) const
    {
        return subject == other.subject && score == other.score && semester == other.semester;
    }

    bool operator<(const ScoreInfo& other) const
    {
        if (score != other.score)
            return score < other.score;
        if (subject != other.subject)
            return subject < other.subject;
        return semester < other.semester;
    }
};

// ==================== MultiMap Value排序基础测试 ====================

/**
 * @brief 测试多重映射的基础value排序功能
 */
TEST(NFShmHashMultiMapWithListTest, BasicMultiMapValueSorting)
{
    printf("========== BasicMultiMapValueSorting Test ==========\n");

    NFShmHashMultiMapWithList<std::string, int, 100> studentScores;
    studentScores.CreateInit();

    // 插入学生成绩数据（允许同一学生有多个成绩）
    studentScores.insert({"Alice", 95});
    studentScores.insert({"Alice", 87});
    studentScores.insert({"Alice", 92});
    studentScores.insert({"Bob", 89});
    studentScores.insert({"Bob", 94});
    studentScores.insert({"Charlie", 91});
    studentScores.insert({"David", 85});
    studentScores.insert({"David", 88});

    printf("Original insertion order:\n");
    for (auto it = studentScores.list_begin(); it != studentScores.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    EXPECT_EQ(studentScores.size(), 8);
    EXPECT_EQ(studentScores.count("Alice"), 3);
    EXPECT_EQ(studentScores.count("Bob"), 2);
    EXPECT_EQ(studentScores.count("David"), 2);

    // 测试1：按成绩升序排序
    studentScores.sort_list();

    printf("\nAfter sort_list() (ascending by score):\n");
    std::vector<int> ascending_scores;
    for (auto it = studentScores.list_begin(); it != studentScores.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        ascending_scores.push_back(it->second);
    }

    // 验证升序排序
    EXPECT_TRUE(std::is_sorted(ascending_scores.begin(), ascending_scores.end()));
    std::vector<int> expected_ascending = {85, 87, 88, 89, 91, 92, 94, 95};
    EXPECT_EQ(ascending_scores, expected_ascending);

    // 测试2：按成绩降序排序
    studentScores.sort_list([](const int a, const int b) {
        return a > b;  // 降序比较
    });

    printf("\nAfter sort_list() (descending by score):\n");
    std::vector<int> descending_scores;
    for (auto it = studentScores.list_begin(); it != studentScores.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        descending_scores.push_back(it->second);
    }

    // 验证降序排序
    EXPECT_TRUE(std::is_sorted(descending_scores.begin(), descending_scores.end(), std::greater<int>()));
    std::vector<int> expected_descending = {95, 94, 92, 91, 89, 88, 87, 85};
    EXPECT_EQ(descending_scores, expected_descending);

    // 验证多重映射的查找功能仍然正常
    auto alice_range = studentScores.equal_range("Alice");
    int alice_count = 0;
    for (auto it = alice_range.first; it != alice_range.second; ++it)
    {
        alice_count++;
    }
    EXPECT_EQ(alice_count, 3);

    printf("BasicMultiMapValueSorting test passed\n");
}

/**
 * @brief 测试按键排序功能：对multimap按学生名字排序
 */
TEST(NFShmHashMultiMapWithListTest, BasicKeySorting)
{
    printf("========== BasicKeySorting Test ==========\n");

    NFShmHashMultiMapWithList<std::string, int, 100> studentScores;
    studentScores.CreateInit();

    // 插入测试数据（同一学生可以有多个分数）
    studentScores.insert({"Zebra", 85});
    studentScores.insert({"Zebra", 90});
    studentScores.insert({"Alice", 95});
    studentScores.insert({"Alice", 88});
    studentScores.insert({"Charlie", 92});
    studentScores.insert({"Bob", 87});
    studentScores.insert({"Bob", 91});
    studentScores.insert({"David", 89});

    printf("Original insertion order:\n");
    for (auto it = studentScores.list_begin(); it != studentScores.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 测试1：按学生姓名升序排序
    studentScores.sort_list_by_key();

    printf("\nAfter sort_list_by_key() (ascending):\n");
    std::vector<std::string> sorted_names;
    for (auto it = studentScores.list_begin(); it != studentScores.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        sorted_names.push_back(it->first);
    }

    // 验证姓名按字母升序排列，同一姓名的多个分数应该相邻
    std::vector<std::string> expected_names = {"Alice", "Alice", "Bob", "Bob", "Charlie", "David", "Zebra", "Zebra"};
    EXPECT_EQ(sorted_names, expected_names);

    // 测试2：按学生姓名降序排序
    studentScores.sort_list_by_key([](const std::string& a, const std::string& b) {
        return a > b;  // 降序比较
    });

    printf("\nAfter sort_list_by_key() (descending):\n");
    std::vector<std::string> descending_names;
    for (auto it = studentScores.list_begin(); it != studentScores.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        descending_names.push_back(it->first);
    }

    // 验证姓名按字母降序排列
    std::vector<std::string> expected_desc_names = {"Zebra", "Zebra", "David", "Charlie", "Bob", "Bob", "Alice", "Alice"};
    EXPECT_EQ(descending_names, expected_desc_names);

    // 验证哈希查找和equal_range仍然正常工作
    EXPECT_EQ(studentScores.size(), 8);
    EXPECT_EQ(studentScores.count("Alice"), 2);
    EXPECT_EQ(studentScores.count("Bob"), 2);
    EXPECT_EQ(studentScores.count("Zebra"), 2);
    
    auto alice_range = studentScores.equal_range("Alice");
    int alice_count = 0;
    for (auto it = alice_range.first; it != alice_range.second; ++it) {
        alice_count++;
    }
    EXPECT_EQ(alice_count, 2);

    printf("BasicKeySorting test passed\n");
}

/**
 * @brief 测试多重映射中复杂对象的value排序
 */
TEST(NFShmHashMultiMapWithListTest, ComplexValueSorting)
{
    printf("========== ComplexValueSorting Test ==========\n");

    NFShmHashMultiMapWithList<int, ScoreInfo, 100> studentRecords;
    studentRecords.CreateInit();

    // 插入学生记录（学生ID -> 多个科目成绩）
    studentRecords.insert({1001, ScoreInfo("Math", 92, "Fall2023")});
    studentRecords.insert({1001, ScoreInfo("Physics", 88, "Fall2023")});
    studentRecords.insert({1001, ScoreInfo("Chemistry", 95, "Spring2024")});

    studentRecords.insert({1002, ScoreInfo("Math", 87, "Fall2023")});
    studentRecords.insert({1002, ScoreInfo("English", 93, "Fall2023")});

    studentRecords.insert({1003, ScoreInfo("Physics", 89, "Spring2024")});
    studentRecords.insert({1003, ScoreInfo("Math", 91, "Spring2024")});
    studentRecords.insert({1003, ScoreInfo("Chemistry", 86, "Spring2024")});

    printf("Original student records:\n");
    for (auto it = studentRecords.list_begin(); it != studentRecords.list_end(); ++it)
    {
        printf("  Student %d: %s = %d (%s)\n", it->first, it->second.subject.c_str(), it->second.score, it->second.semester.c_str());
    }

    // 测试1：按分数排序
    studentRecords.sort_list_by_value([](const ScoreInfo& a, const ScoreInfo& b)
    {
        return a.score < b.score;
    });

    printf("\nAfter sorting by score:\n");
    std::vector<int> scores;
    for (auto it = studentRecords.list_begin(); it != studentRecords.list_end(); ++it)
    {
        printf("  Student %d: %s = %d (%s)\n", it->first, it->second.subject.c_str(), it->second.score, it->second.semester.c_str());
        scores.push_back(it->second.score);
    }

    EXPECT_TRUE(std::is_sorted(scores.begin(), scores.end()));

    // 测试2：按科目排序
    studentRecords.sort_list_by_value([](const ScoreInfo& a, const ScoreInfo& b)
    {
        return a.subject < b.subject;
    });

    printf("\nAfter sorting by subject:\n");
    std::vector<std::string> subjects;
    for (auto it = studentRecords.list_begin(); it != studentRecords.list_end(); ++it)
    {
        printf("  Student %d: %s = %d (%s)\n", it->first, it->second.subject.c_str(), it->second.score, it->second.semester.c_str());
        subjects.push_back(it->second.subject);
    }

    EXPECT_TRUE(std::is_sorted(subjects.begin(), subjects.end()));

    // 测试3：复合排序：先按学期，再按分数
    studentRecords.sort_list_by_value([](const ScoreInfo& a, const ScoreInfo& b)
    {
        if (a.semester != b.semester)
        {
            return a.semester < b.semester;
        }
        return a.score < b.score;
    });

    printf("\nAfter sorting by semester then score:\n");
    std::string prev_semester = "";
    int prev_score = 0;
    bool is_correctly_sorted = true;

    for (auto it = studentRecords.list_begin(); it != studentRecords.list_end(); ++it)
    {
        printf("  Student %d: %s = %d (%s)\n", it->first, it->second.subject.c_str(), it->second.score, it->second.semester.c_str());

        if (!prev_semester.empty())
        {
            if (it->second.semester < prev_semester || (it->second.semester == prev_semester && it->second.score < prev_score))
            {
                is_correctly_sorted = false;
            }
        }
        prev_semester = it->second.semester;
        prev_score = it->second.score;
    }

    EXPECT_TRUE(is_correctly_sorted);

    // 验证多重映射查找功能
    EXPECT_EQ(studentRecords.count(1001), 3);
    EXPECT_EQ(studentRecords.count(1002), 2);
    EXPECT_EQ(studentRecords.count(1003), 3);

    printf("ComplexValueSorting test passed\n");
}

/**
 * @brief 测试多重映射特有的键相邻性保持
 */
TEST(NFShmHashMultiMapWithListTest, KeyAdjacencyPreservation)
{
    printf("========== KeyAdjacencyPreservation Test ==========\n");

    NFShmHashMultiMapWithList<std::string, int, 100> categoryMap;
    categoryMap.CreateInit();

    // 插入分类数据
    categoryMap.insert({"Fruit", 100});
    categoryMap.insert({"Fruit", 80});
    categoryMap.insert({"Fruit", 90});
    categoryMap.insert({"Vegetable", 70});
    categoryMap.insert({"Vegetable", 85});
    categoryMap.insert({"Meat", 120});
    categoryMap.insert({"Meat", 110});
    categoryMap.insert({"Meat", 95});

    printf("Original data:\n");
    for (auto it = categoryMap.list_begin(); it != categoryMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 按value排序但保持key的语义
    categoryMap.sort_list();

    printf("\nAfter sorting by value:\n");
    for (auto it = categoryMap.list_begin(); it != categoryMap.list_end(); ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
    }

    // 验证排序正确性
    std::vector<int> sorted_values;
    for (auto it = categoryMap.list_begin(); it != categoryMap.list_end(); ++it)
    {
        sorted_values.push_back(it->second);
    }
    EXPECT_TRUE(std::is_sorted(sorted_values.begin(), sorted_values.end()));

    // 验证equal_range仍然有效
    auto fruit_range = categoryMap.equal_range("Fruit");
    int fruit_count = 0;
    printf("\nFruit items after sorting:\n");
    for (auto it = fruit_range.first; it != fruit_range.second; ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        fruit_count++;
    }
    EXPECT_EQ(fruit_count, 3);

    auto vegetable_range = categoryMap.equal_range("Vegetable");
    int vegetable_count = 0;
    printf("\nVegetable items after sorting:\n");
    for (auto it = vegetable_range.first; it != vegetable_range.second; ++it)
    {
        printf("  %s: %d\n", it->first.c_str(), it->second);
        vegetable_count++;
    }
    EXPECT_EQ(vegetable_count, 2);

    printf("KeyAdjacencyPreservation test passed\n");
}

/**
 * @brief 测试与传统sort_list的兼容性和功能区别
 */
TEST(NFShmHashMultiMapWithListTest, SortCompatibilityComparison)
{
    printf("========== SortCompatibilityComparison Test ==========\n");

    NFShmHashMultiMapWithList<int, std::string, 100> testMap;
    testMap.CreateInit();

    // 插入测试数据
    testMap.insert({1, "zebra"});
    testMap.insert({1, "apple"});
    testMap.insert({2, "banana"});
    testMap.insert({2, "cherry"});
    testMap.insert({3, "date"});

    // 保存原始数据用于比较
    std::vector<std::pair<int, std::string>> original_data;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        original_data.emplace_back(it->first, it->second);
    }

    printf("Original data:\n");
    for (const auto& pair : original_data)
    {
        printf("  %d: %s\n", pair.first, pair.second.c_str());
    }

    // 测试1：使用sort_list_by_key按key排序
    testMap.sort_list_by_key();

    printf("\nAfter sort_list_by_key():\n");
    std::vector<std::pair<int, std::string>> key_sorted_data;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %d: %s\n", it->first, it->second.c_str());
        key_sorted_data.emplace_back(it->first, it->second);
    }

    // 恢复原始数据
    testMap.clear();
    for (const auto& pair : original_data)
    {
        testMap.insert({pair.first, pair.second});
    }

    // 测试2：使用sort_list按value排序
    testMap.sort_list();

    printf("\nAfter sort_list:\n");
    std::vector<std::pair<int, std::string>> value_sorted_data;
    for (auto it = testMap.list_begin(); it != testMap.list_end(); ++it)
    {
        printf("  %d: %s\n", it->first, it->second.c_str());
        value_sorted_data.emplace_back(it->first, it->second);
    }

    // 验证两种排序的结果不同
    EXPECT_NE(key_sorted_data, value_sorted_data);

    // 验证value排序确实按value排序了
    std::vector<std::string> values_only;
    for (const auto& pair : value_sorted_data)
    {
        values_only.push_back(pair.second);
    }
    EXPECT_TRUE(std::is_sorted(values_only.begin(), values_only.end()));

    // 验证多重映射功能仍然正常
    EXPECT_EQ(testMap.count(1), 2);
    EXPECT_EQ(testMap.count(2), 2);
    EXPECT_EQ(testMap.count(3), 1);

    printf("SortCompatibilityComparison test passed\n");
}

/**
 * @brief 测试大量数据下的性能和正确性
 */
TEST(NFShmHashMultiMapWithListTest, LargeDataPerformance)
{
    printf("========== LargeDataPerformance Test ==========\n");

    constexpr int TEST_SIZE = 500;
    constexpr int VALUES_PER_KEY = 3;
    NFShmHashMultiMapWithList<int, int, TEST_SIZE * VALUES_PER_KEY + 100> perfMap;
    perfMap.CreateInit();

    // 生成测试数据：每个key有多个value
    std::vector<std::pair<int, int>> test_data;
    for (int key = 1; key <= TEST_SIZE; ++key)
    {
        for (int val = 0; val < VALUES_PER_KEY; ++val)
        {
            int value = (key * 17 + val * 23) % 1000;
            test_data.emplace_back(key, value);
        }
    }

    // 随机打乱插入顺序
    std::random_device rd;
    std::mt19937 gen(rd());
    std::shuffle(test_data.begin(), test_data.end(), gen);

    // 插入数据
    for (const auto& pair : test_data)
    {
        perfMap.insert({pair.first, pair.second});
    }

    printf("Performance test with %d elements (%d keys, %d values per key):\n", (int)test_data.size(), TEST_SIZE, VALUES_PER_KEY);

    EXPECT_EQ(perfMap.size(), test_data.size());

    // 测试排序性能
    auto start = std::chrono::high_resolution_clock::now();
    perfMap.sort_list();
    auto end = std::chrono::high_resolution_clock::now();
    auto sort_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

    printf("sort_list() took %lld microseconds\n", sort_time.count());

    // 验证排序正确性
    std::vector<int> sorted_values;
    for (auto it = perfMap.list_begin(); it != perfMap.list_end(); ++it)
    {
        sorted_values.push_back(it->second);
    }
    EXPECT_TRUE(std::is_sorted(sorted_values.begin(), sorted_values.end()));

    // 验证多重映射功能
    for (int key = 1; key <= TEST_SIZE; ++key)
    {
        EXPECT_EQ(perfMap.count(key), VALUES_PER_KEY);
    }

    // 测试自定义比较器的性能
    start = std::chrono::high_resolution_clock::now();
    perfMap.sort_list([](const int& a, const int& b)
    {
        return (a % 100) < (b % 100); // 按模100排序
    });
    end = std::chrono::high_resolution_clock::now();
    auto custom_sort_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

    printf("sort_list(custom_comp) took %lld microseconds\n", custom_sort_time.count());

    // 验证自定义排序结果
    std::vector<int> mod_values;
    for (auto it = perfMap.list_begin(); it != perfMap.list_end(); ++it)
    {
        mod_values.push_back(it->second % 100);
    }
    EXPECT_TRUE(std::is_sorted(mod_values.begin(), mod_values.end()));

    printf("LargeDataPerformance test passed\n");
}

/**
 * @brief 测试边界情况和错误处理
 */
TEST(NFShmHashMultiMapWithListTest, EdgeCasesAndErrorHandling)
{
    printf("========== EdgeCasesAndErrorHandling Test ==========\n");

    // 测试1：空容器
    printf("Test 1: Empty container\n");
    {
        NFShmHashMultiMapWithList<std::string, int, 10> emptyMap;
        emptyMap.CreateInit();

        emptyMap.sort_list();
        emptyMap.sort_list();
        emptyMap.sort_list([](const int& a, const int& b) { return a < b; });

        EXPECT_EQ(emptyMap.size(), 0);
        EXPECT_TRUE(emptyMap.empty());
        printf("Empty container test passed\n");
    }

    // 测试2：所有元素相同值
    printf("Test 2: All same values\n");
    {
        NFShmHashMultiMapWithList<std::string, int, 20> sameMap;
        sameMap.CreateInit();

        sameMap.insert({"A", 100});
        sameMap.insert({"A", 100});
        sameMap.insert({"B", 100});
        sameMap.insert({"C", 100});
        sameMap.insert({"D", 100});

        sameMap.sort_list();

        // 所有值应该都是100
        for (auto it = sameMap.list_begin(); it != sameMap.list_end(); ++it)
        {
            EXPECT_EQ(it->second, 100);
        }

        EXPECT_EQ(sameMap.size(), 5);
        printf("Same values test passed\n");
    }

    // 测试3：单一key多个value
    printf("Test 3: Single key with multiple values\n");
    {
        NFShmHashMultiMapWithList<int, std::string, 20> singleKeyMap;
        singleKeyMap.CreateInit();

        singleKeyMap.insert({1, "zebra"});
        singleKeyMap.insert({1, "apple"});
        singleKeyMap.insert({1, "banana"});
        singleKeyMap.insert({1, "cherry"});

        singleKeyMap.sort_list();

        std::vector<std::string> sorted_values;
        for (auto it = singleKeyMap.list_begin(); it != singleKeyMap.list_end(); ++it)
        {
            sorted_values.push_back(it->second);
        }

        std::vector<std::string> expected = {"apple", "banana", "cherry", "zebra"};
        EXPECT_EQ(sorted_values, expected);
        EXPECT_EQ(singleKeyMap.count(1), 4);

        printf("Single key multiple values test passed\n");
    }

    printf("EdgeCasesAndErrorHandling test passed\n");
}
